package demo.spring.batis.accesstocken;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by neil on 2017/1/20.
 * 参考：https://github.com/jwtk/jjwt
 */
public class JWTUtil {
    private static Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    private final static String secretKey = "123456789";//TODO 部署是需要统一配置

    public static String jwtGen(TokenInfo tokenInfo) {
        try {
            Map<String, Object> header = new HashMap<>();
            header.put("type", "JWT");
            header.put("alg", "HS512");
            String token = Jwts.builder().setSubject(tokenInfo.getUuserId())
//                .setExpiration(new Date())
                    .claim("expir", tokenInfo.getExpir())
                    .claim("uplatId",tokenInfo.getUplatId())
                    .setIssuer(tokenInfo.getIssuser())
                    .setHeader(header)
                    .signWith(SignatureAlgorithm.HS512, secretKey)
                    .compact();

            return token;
        } catch (Exception e) {
            logger.error("exception: JWTGen", e);
            return null;
        }
    }

    public static TokenInfo parseJWTInfo(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
//        String sign = Jwts.parser().setSigningKey("123456789").parseClaimsJws(token).getSignature();
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setIssuser(claims.getIssuer());
            tokenInfo.setExpir((Long)claims.get("expir"));
            tokenInfo.setUplatId((String)claims.get("uplatId"));
            tokenInfo.setUuserId(claims.getSubject());
            tokenInfo.setIssuser((String) claims.getIssuer());
            return tokenInfo;
        } catch (Exception e) {
            logger.error("exception: getJWTInfo", e);
            return null;
        }
    }
}
